package tutorial;

import org.junit.Test;

public class UniqueChar {
	
	@Test
	public void testIsUniqueChars() {
		boolean duplicated = isUniqueChars("adbdeckeke");
		assert(duplicated == false);
		
		boolean unique = isUniqueChars("adbcef");
		assert(unique == true);
		
	}
	
	@Test
	public void testRemoveDuplicated() {
		String str = "FOLLOW UP";
		String str1 = "adddda";
		String str2 = "ddddd";
		String str3 = "abcde";
		char[] array = str.toCharArray();
		char[] array1 = str1.toCharArray();
		char[] array2 = str2.toCharArray();
		char[] array3 = str3.toCharArray();
		
		removeDuplicatedChar(array3);
		
		removeDuplicates(array2);
	}
	
	/*
	 * Only for char set ASCII
	 */
	public boolean isUniqueChars(String str) {	
		boolean[] charSet = new boolean[256];
		for(int i = 0; i < str.length(); i++) {
			int val = str.charAt(i);
			if (charSet[val]) return false;
			charSet[val] = true;
		}
		return true;
	}
	
	public void removeDuplicatedChar(char[] array) {
		if (array == null) return;
		
		int len = array.length;
		
		if (len < 2) return;
		
		for (int i = 1; i < len; i++) {
			for (int j = 0; j < i; j++) {
				if (array[i] == array[j]) {
					array[i] = 0;
				}
			}
		}
		
		System.out.println(new String(array));
	}
	
	public void removeDuplicates(char[] str) {
		if (str == null) return;
		int len = str.length;
		if (len < 2) return;
		
		int tail = 1;
		
		for (int i = 1; i < len; i++) {
			int j;
			for (j = 0; j < tail; ++j) {
				if (str[i] == str[j]) break;
			}
			
			if (j == tail) {
				str[tail] = str[i];
				++tail;
			}
		}
		str[tail] = 0;
		
		System.out.println(new String(str));
	}
}
